package me.geolo.photopicker.main;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.UUID;

import me.geolo.photopicker.R;
import me.geolo.photopicker.fragment.ImagePagerFragment;

import static me.geolo.photopicker.main.PhotoPicker.KEY_SELECTED_PHOTOS;
import static me.geolo.photopicker.main.PhotoPreview.EXTRA_CURRENT_ITEM;
import static me.geolo.photopicker.main.PhotoPreview.EXTRA_PHOTOS;
import static me.geolo.photopicker.main.PhotoPreview.EXTRA_SHOW_DELETE;

/**
 * Created by donglua on 15/6/24.
 */
public class PhotoPagerActivity extends AppCompatActivity {

    private ImagePagerFragment pagerFragment;

    private ActionBar actionBar;
    private boolean showDelete;

    private View mProgressBar;
    private boolean isDownloading = false;
    private boolean showDownload = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.__picker_activity_photo_pager);

        int currentItem = getIntent().getIntExtra(EXTRA_CURRENT_ITEM, 0);
        List<String> paths = getIntent().getStringArrayListExtra(EXTRA_PHOTOS);
        showDelete = getIntent().getBooleanExtra(EXTRA_SHOW_DELETE, true);
        showDownload = getIntent().getBooleanExtra(PhotoPreview.EXTRA_SHOW_DOWNLOAD, false);

        if (pagerFragment == null) {
            pagerFragment = (ImagePagerFragment) getSupportFragmentManager().findFragmentById(R.id.photoPagerFragment);
        }
        pagerFragment.setPhotos(paths, currentItem);

        mProgressBar = findViewById(R.id.mProgressBar);
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        actionBar = getSupportActionBar();

        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            updateActionBarTitle();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                actionBar.setElevation(25);
            }
        }

        pagerFragment.getViewPager().addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                updateActionBarTitle();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (showDelete) {
            getMenuInflater().inflate(R.menu.__picker_menu_preview, menu);
        }
        if (showDownload) {
            getMenuInflater().inflate(R.menu.__picker_menu_download, menu);
        }
        return true;
    }

    @Override
    public void onBackPressed() {

        Intent intent = new Intent();
        intent.putExtra(KEY_SELECTED_PHOTOS, pagerFragment.getPaths());
        setResult(RESULT_OK, intent);
        finish();

        super.onBackPressed();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }

        if (item.getItemId() == R.id.download && pagerFragment != null) {
            if (!isDownloading) {
                Log.v("geolo", "geolo img isDownloading");
                int index = pagerFragment.getCurrentItem();
                String imgUrl = pagerFragment.getPaths().get(index);
                if (!TextUtils.isEmpty(imgUrl) && imgUrl.startsWith("http")) {
                    savePicture(imgUrl, mProgressBar);
                }
                return true;
            } else {
                return false;
            }
        }

        if (item.getItemId() == R.id.delete) {
            final int index = pagerFragment.getCurrentItem();

            final String deletedPath = pagerFragment.getPaths().get(index);

            Snackbar snackbar =
                Snackbar.make(pagerFragment.getView(), R.string.__picker_deleted_a_photo, Snackbar.LENGTH_LONG);

            if (pagerFragment.getPaths().size() <= 1) {

                // show confirm dialog
                new AlertDialog.Builder(this).setTitle(R.string.__picker_confirm_to_delete)
                    .setPositiveButton(R.string.__picker_yes, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                            pagerFragment.getPaths().remove(index);
                            pagerFragment.getViewPager().getAdapter().notifyDataSetChanged();
                            onBackPressed();
                        }
                    })
                    .setNegativeButton(R.string.__picker_cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    })
                    .show();

            } else {

                snackbar.show();

                pagerFragment.getPaths().remove(index);
                pagerFragment.getViewPager().getAdapter().notifyDataSetChanged();
            }

            snackbar.setAction(R.string.__picker_undo, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (pagerFragment.getPaths().size() > 0) {
                        pagerFragment.getPaths().add(index, deletedPath);
                    } else {
                        pagerFragment.getPaths().add(deletedPath);
                    }
                    pagerFragment.getViewPager().getAdapter().notifyDataSetChanged();
                    pagerFragment.getViewPager().setCurrentItem(index, true);
                }
            });

            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void updateActionBarTitle() {
        if (actionBar != null) {
            actionBar.setTitle(getString(R.string.__picker_image_index,
                pagerFragment.getViewPager().getCurrentItem() + 1, pagerFragment.getPaths().size()));
        }
    }

    // Glide保存图片
    public void savePicture(String url, final View progressLayout) {
        isDownloading = true;
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.VISIBLE);
        }

        Glide.with(this).asFile().load(Uri.parse(url)).listener(new RequestListener<File>() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<File> target, boolean b) {
                if (progressLayout != null) {
                    progressLayout.setVisibility(View.GONE);
                }
                if (e != null) {
                    e.printStackTrace();
                }
                isDownloading = false;
                return false;
            }

            @Override
            public boolean onResourceReady(File bitmap, Object o, Target<File> target, DataSource dataSource,
                boolean b) {
                saveBmp(PhotoPagerActivity.this, bitmap);
                if (progressLayout != null) {
                    progressLayout.setVisibility(View.GONE);
                }
                isDownloading = false;
                return false;
            }
        }).submit();
    }

    private void saveBmp(Context context, File resource) {
        if (resource != null && resource.exists()) {
            String downloadPath = null;
            try {
                downloadPath = MediaStore.Images.Media.insertImage(context.getContentResolver(), resource.getPath(),
                    UUID.randomUUID().toString(), "geolo_photo_save");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            if (!TextUtils.isEmpty(downloadPath)) {
                Toast.makeText(context, "图片已保存到相册", Toast.LENGTH_SHORT).show();
                Log.v("geolo", "geolo img url : " + downloadPath);
            }
        }
    }
}
